package com.yzz.shopping.ui.adapter

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.text.SpannableString
import android.text.Spanned
import android.text.TextUtils
import android.text.style.ImageSpan
import android.text.style.StrikethroughSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.*
import com.bumptech.glide.request.RequestOptions
import com.yzz.shopping.GlideHttpUtils
import com.yzz.shopping.GlideHttpUtils.GlideListener
import com.yzz.shopping.R
import com.yzz.shopping.entity.GlideRecommendBean
import com.yzz.shopping.ui.dialog.DialogUtils
import com.yzz.shopping.ui.viewholder.ShoppingViewHolder
import com.yzz.shopping.utils.*
import com.yzz.shopping.viewmodel.GlideViewModel


/**
 * @Author : yangzuozhe
 * @Time : On 2022/2/23 14:54
 *
 * @Description : ShoppingAdapter
 */
open class ShoppingAdapter(
    private var mActivty: FragmentActivity?,
    private var mList: MutableList<GlideRecommendBean?>,
    private val mIsSearch: Boolean,
) :
    RecyclerView.Adapter<ShoppingViewHolder>() {

    companion object {
        private var canOpenList = ArrayList<String>()
    }

    private fun canAdminPostClick(cxt: Context?, admin: String): Boolean {
        if (canOpenList.isNullOrEmpty()) {
            val menuStr = ShoppingPreferenceUtil.getWhiteListParam(cxt)
            if (!menuStr.isNullOrEmpty()) {
                canOpenList.addAll(menuStr.split(","))
            }
        }
        return canOpenList.contains(admin)
    }

    @SuppressLint("NotifyDataSetChanged")
    fun loadMore(list: MutableList<GlideRecommendBean?>) {
        mList.addAll(list)
        notifyDataSetChanged()
    }


    @SuppressLint("NotifyDataSetChanged")
    fun refreshData(list: MutableList<GlideRecommendBean?>) {
        mList = list
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ShoppingViewHolder =
        if (!mIsSearch) {
            ShoppingViewHolder(
                LayoutInflater.from(parent.context)
                    .inflate(R.layout.item_shopping_adapter, parent, false)
            )
        } else {
            ShoppingViewHolder(
                LayoutInflater.from(parent.context)
                    .inflate(R.layout.item_shopping_search, parent, false)
            )
        }


    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: ShoppingViewHolder, position: Int) {
        val bean = mList[position]

        holder.mShoppingImg?.let {
            mActivty?.let { activity ->
                if (!CheckActivityUtils.isDestroy(activity)) {
                    Glide.with(activity).asBitmap().load(bean?.imageUrl).apply(
                        RequestOptions().transform(RoundedCorners(ToolsUtils.dpToPx(6)))
                            .placeholder(R.mipmap.icon_default)
                            .dontAnimate()
                            .fallback(R.mipmap.icon_default)
                            .error(R.mipmap.icon_default)
                    ).into(it)
                }
            }
        }
        holder.mTvSaveMoney?.text = ""
        holder.mTvPrice?.text = "¥${bean?.lowestCouponPrice}"
        val specialPrice = bean?.discount
        if (TextUtils.equals(specialPrice, "0") || TextUtils.isEmpty(specialPrice)) {
//            holder.mGroupSaveMoney?.visibility = View.GONE
            setSaveMoneyShow(false, holder)
        } else {
            setSaveMoneyShow(true, holder)
//            holder.mGroupSaveMoney?.visibility = View.VISIBLE
            if (mIsSearch) {
                holder.mTvSaveMoney?.text = "${specialPrice}元券"
            } else {
                holder.mTvSaveMoney?.text = "领${specialPrice}元券"
            }
        }

        val spann = SpannableString("  ${bean?.skuName}")
        val imageSpan =
            holder.mIvShoppingType?.context?.let {
                ImageSpan(it, getImgType(bean?.ecName ?: ""))
            }
        spann.setSpan(imageSpan, 0, 1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE)
        holder.mIvShoppingType?.text = spann
        holder.mTvSellNumber?.text = "已售${bean?.inOrderCount30Days}"
        holder.mTvShoppingShopName?.text = bean?.shopName
        val spann2 = if (mIsSearch) {
            SpannableString("¥${bean?.price}")
        } else {
            SpannableString("原价¥${bean?.price}")
        }
        val strikethroughSpan = StrikethroughSpan()
        spann2.setSpan(strikethroughSpan, 0, spann2.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        holder.mTvOriginalPrice?.text = spann2
        holder.mShoppingView?.setOnClickListener {
            val newBean = mList[position] ?: return@setOnClickListener
            if (NoFastClickUtils.isFastClick()) {
                return@setOnClickListener
            }
            if (TextUtils.equals(newBean.ec, GlideViewModel.IEcType.TAO_BAO.toString())) {
                it?.context?.let { it1 ->
                    JumpToOtherApp.launchAppActivity(
                        it1,
                        newBean.ec,
                        newBean.couponUrl
                    )
                }
            } else {
                jumpUrl(it.context, newBean.materialUrl, newBean.couponUrl, newBean.ec)
            }
        }
        holder.mShoppingView?.setOnLongClickListener {
            val newBean = mList[position] ?: return@setOnLongClickListener false
            ShoppingAppInitUtils.instance.mUserId?.let {
                ShoppingAppInitUtils.instance.mUserToken?.let { to ->
                    if (canAdminPostClick(mActivty, it)) {
                        postAdminGoods(to, newBean)
                    }
                    return@setOnLongClickListener true
                }
            }
            false
        }
    }

    private fun setSaveMoneyShow(isShow: Boolean, holder: ShoppingViewHolder?) {
        if (isShow) {
            holder?.mTvOriginalPrice?.visibility = View.VISIBLE
            holder?.mTvSaveMoney?.visibility = View.VISIBLE
            holder?.mTvSaveMoney?.layoutParams?.apply {
                width = ViewGroup.LayoutParams.WRAP_CONTENT
                height = ViewGroup.LayoutParams.WRAP_CONTENT
            }
        } else {
            holder?.mTvOriginalPrice?.visibility = View.GONE
            holder?.mTvSaveMoney?.visibility = View.GONE
            holder?.mTvSaveMoney?.layoutParams?.apply {
                width = 0
                height = 0
            }
        }
    }

    private fun postAdminGoods(userToken: String, bean: GlideRecommendBean) {
        mActivty?.let { activity ->
            DialogUtils.instance.showIsAdminPostGoods(activity) {
                GlideHttpUtils.getInstacne()
                    .postAdminUpGoods(userToken, bean, object : GlideListener<String> {
                        override fun onSuccess(bean: String?) {
                            ToastUtils.showShort(bean)
                        }

                        override fun onError(e: String?) {
                            ToastUtils.showShort("失败")
                        }

                    })
            }
        }
    }

    private fun jumpUrl(context: Context, materialUrl: String?, couponUrl: String?, ec: String?) {
        GlideHttpUtils.getInstacne().requestJumUrl(
            materialUrl,
            couponUrl,
            ec,
            object : GlideListener<String?> {


                override fun onError(e: String) {
                    ToastUtils.showShort("网络请求错误")
                }

                override fun onSuccess(str: String?) {
                    if (str != null && ec != null) {
                        JumpToOtherApp.launchAppActivity(context, ec, str)
                    } else {
                        ToastUtils.showShort("网络请求错误")
                    }


                }
            })

    }

    private fun getImgType(ecName: String): Int {
        return when (ecName) {
            GlideViewModel.IEcName.TAO_BAO_NAME -> {
                R.mipmap.icon_taobao
            }
            GlideViewModel.IEcName.JING_DONG_NAME -> {
                R.mipmap.icon_jingdong
            }
            GlideViewModel.IEcName.PIN_DUODUO_NAME -> {
                R.mipmap.icon_pinduoduo
            }
            GlideViewModel.IEcName.TIAN_MAO -> {
                R.mipmap.icon_tianmao
            }
            else -> {
                0
            }
        }
    }

    fun interface IItemLongClickListener {
        fun onClick(bean: GlideRecommendBean)
    }

    override fun getItemCount(): Int {
        return mList.size
    }
}